package org.bim.view.drag.design.controller;

import org.bim.view.drag.design.api.vo.R;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.bim.view.drag.design.model.HttpResult;
import org.bim.view.drag.design.model.Page;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;

/**
 * @author bim-view
 * @date 2021/12/17 2:34 下午
 */
@Slf4j
@ControllerAdvice
@NoArgsConstructor
public class ResponseBodyAdvice implements org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice<Object> {
    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
//        if (!request.getURI().getPath().startsWith(WebMvcConfigurer.PREFIX_FOR_BIG_SCREEN_DESIGNER)) {
//            return body;
//        }

        Object res;
        if (body instanceof HttpResult) {
            HttpResult result = (HttpResult) body;
            R r = new R();
            r.setCode(result.getCode());
            r.setData(result.getData());
            r.setMsg(result.getMessage());
            r.setSuccess(result.isStatus());
            res = r;
            exchangePage(r);
        } else {
            res = body;
        }

        return res;
    }

    private void exchangePage(R r) {
        if (r.getData() instanceof Page) {
            Page page = (Page) r.getData();
            org.bim.view.drag.design.api.vo.Page nPage = new org.bim.view.drag.design.api.vo.Page();
            nPage.setPages(page.getPageTotal());
            nPage.setCurrent(page.getPageNum());
            nPage.setTotal(page.getTotal().intValue());
            nPage.setSize(page.getPageSize());
            nPage.setRecords(page.getList());
            r.setData(nPage);
        }
    }
}
